//
//  WBMainViewController.swift
//  SinaWebo
//
//  Created by 亚杏 on 2017/5/5.
//  Copyright © 2017年 oms. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController,UITabBarControllerDelegate {
    //定时器
    private var timer: Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildVC()
        setupMiddleBtn()
        setupTimer()
        setupNewFeature()//设置新特性

        //设置代理 
        delegate = self
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLoginAction), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)

    }

    //------------------------------
    //MARK:新特性视图
    private func setupNewFeature(){
        
        //判断是否登录
        if !WBNetworkManager.shared.userLogin{
            return
        }

        //检查版本是否更新，如果更新，显示新特性，否则显示欢迎
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        //添加视图
        v.frame = view.bounds
        view.addSubview(v)
    }

    //计算型属性,不占用存储空间
    private var isNewVersion: Bool{
        //取当前版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        //取保存在Document目录中之前的版本号
        let path = ("version" as NSString).cz_appendDocumentDir()
        let sandBoxVersion = (try? String(contentsOfFile: path!)) ?? ""
        //将当前版本号保存在沙盒
       _ = try? currentVersion.write(toFile: path!, atomically: true, encoding: .utf8)
        //返回两个版本号是否一致
        return currentVersion != sandBoxVersion
//        return currentVersion == sandBoxVersion

    }

    //------------------------------


    deinit {
        timer?.invalidate()
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }

    private func setupTimer (){

        timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }

    //时钟触发方法
    @objc private func updateTimer(){

        if !WBNetworkManager.shared.userLogin {
            return
        }

        //可发起网络请求，获得badgeNumber
        self.tabBar.items?[0].badgeValue = "3"
        //设置App的badgeNumber
        //从ios 8.0之后必须得用户授权才能显示
        UIApplication.shared.applicationIconBadgeNumber = 1
    }


    //私有控件
    //中间按钮
    private lazy var middleBtn: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")



    private func setupMiddleBtn(){
        tabBar.addSubview(middleBtn)

        //计算按钮宽度
        let count = CGFloat(childViewControllers.count)
        //-1是为了将中间的按钮区域扩大，将容错点覆盖
//        let w = tabBar.bounds.width / count - 1
        //由于更改了shouldSelectTabbaritem的方法，可以不用修改w，增加了一个判断，如果是UIViewController的话就点击tabbarItem无效
        let w = tabBar.bounds.width / count
        middleBtn.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        middleBtn.addTarget(self, action: #selector(middleBtnClick), for: .touchUpInside)

    }

    //MARK:按钮监听方法
    //@objc，能够保证此方法在本类私有，当前对象能访问，不会暴露
    @objc private func middleBtnClick(){

        print("点击写微博")
        //FIXME: 0> 判断是否登录
        //1. 实例化视图
        let v = WBComposeTypeView.composeTypeView()

        //MARK: 弱引用  2. 显示视图, v必须弱引用
        v.show { [weak v] (clsName) in
            print(clsName ?? "")
            //展现撰写微博控制器
            guard let clsName = clsName,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type else{
                v?.removeFromSuperview()
                return
            }

            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)

            //让导航控制器强行更新约束 - 会更新所有子视图的约束
            //先更新，再展示，则不会在展示过程中显示动画
            nav.view.layoutIfNeeded()

            self.present(nav, animated: true, completion: {
                v?.removeFromSuperview()
            })

        }
    
    }

    //MARK:通知监听方法
    @objc private func userLoginAction(n: Notification){

        print("用户登录通知 \(n)")
        
        var when = DispatchTime.now()
        
        //判断n.object是否有值,如果有值就提示用户重新登录 
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(.custom)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时,请重新登录")
            //个性延迟时间 
            when = DispatchTime.now()+2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            let nav = UINavigationController(rootViewController:WBOAuthViewController())
            self.present(nav, animated: true, completion: nil)

        }
       
    }

    //MARK:设置所有子控制器，加载本地json的tabbar
    private func setupChildVC(){

        //0、获取沙盒请求下来存的路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")

        //1.加载data
        var data = NSData(contentsOfFile: jsonPath)

        //判断，如果data无内容，说明本地沙盒无数据，加载本地的
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        //data一定有值，反序列化
     //从bundle加载配置的json
       guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String :AnyObject]]
        else{
            return
        }


//        let array:[[String: Any]] = [
//            ["clsName":"WBHomeViewController", "title":"首页", "imageName":"home","visitorInfo":["imageName":"", "message":"关注一些人，回这里看看有什么惊喜"]],
//
//            ["clsName":"WBMessageViewController", "title":"消息", "imageName":"message_center","visitorInfo":["imageName":"visitordiscover_image_message", "message":"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
//
//             ["clsName":"UIViewController"],
//
//             ["clsName":"WBDiscoveryViewController", "title":"发现", "imageName":"discover","visitorInfo":["imageName":"visitordiscover_image_message", "message":"登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"]],
//
//              ["clsName":"WBProfileViewController", "title":"我", "imageName":"profile","visitorInfo":["imageName":"visitordiscover_image_profile", "message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]]
//
//
//        ]

        //测试数据格式是否正确 - 转换成plist,更直观
       // (array as NSArray).write(toFile: "/Users/oms/Desktop/demo.plist", atomically: true)
        //数组转json
//        let data = try? JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        let fileURL = NSURL.fileURL(withPath: "/Users/oms/Desktop/demo.json")
//        (data! as NSData).write(to: fileURL, atomically:true)


        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }

        viewControllers = arrayM
        
    }

    //使用字典创建一个子控制器
    private func controller(dict:[String: AnyObject]) -> UIViewController{

        //1.取得字典内容
        guard let clsName = dict["clsName"] as?String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            //1> 将clsName转换成class
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let visitorDict = dict["visitorInfo"] as?[String: String]

            else{
                return UIViewController()
        }

        //2.创建视图控制器
        let vc = cls.init()
        vc.title = title

        //设置控制器的访客信息字典
        vc.visitorInfoDict = visitorDict
        vc.tabBarItem.image = UIImage(named:"tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named:"tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)

        //设置tabbar标题字体
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .selected)
        //系统默认是12号字
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13)], for: .normal)

        //会调用push方法
        let nav = WBNavViewController(rootViewController: vc)
        return nav



    }


    //设置支持的方向后，当前的控制器和子控制器都会遵守这个方向
    //- 如果播放视频，通常是通过modal展现的
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }

    //MARK:UITabBarControllerDelegate
    //将要选择tabbaritem
    /// - Parameters:
    /// - tabBarController: tabBarController description
    /// - viewController: viewController description
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到\(viewController)")
        //1.获取控制器在数组中的索引 
        let index = (childViewControllers as NSArray).index(of: viewController)
        //判断当时索引是首页时，重复点击首页按钮
        if selectedIndex == 0 && index == selectedIndex {
            print("点击首页")
            //让表格滚动到顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            //滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            //刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: {
                vc.loadData()
            })
            //清除tabItem的badgeNum
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }


        return !viewController.isMember(of: UIViewController.self)
    }

}

//除了像OC中的分类，还可以用来切分代码块，可以把相近功能的函数 放在一个extension中，便于维护
//和OC分类一样，extension中不能定义属性，只能定义方法
extension WBMainViewController{


}
